import datetime
import os
import re
import shutil
from PyQt5 import QtWidgets
from PyQt5.QtCore import QRect, QDate, Qt
from PyQt5.QtGui import QPainter, QPixmap, QImage, QBrush, QColor, QPen, QFont
from PyQt5.QtWidgets import QCalendarWidget, QApplication, QDateEdit, QMessageBox
from PyQt5.QtWidgets import (QTableWidget,
                             QTableWidgetItem, QWidget, QPushButton, QVBoxLayout, QDialog,QLineEdit,
                             QHBoxLayout,QTextEdit)
from bs4 import BeautifulSoup
from pandas import DataFrame
from src.forward.base.RightWidget import RightWidget
from src.forward.base.bean import forward, Table_ABC, CustomQPushButton


@forward(name='班级情况')
class ClassRoom(RightWidget):

    def __init__(self):
        super().__init__()
        create_class=QWidget()
        create_class_layout=QHBoxLayout()
        self.date_class=QDateEdit()
        self.date_class.setCalendarPopup(True)
        self.date_class.setDate(QDate.currentDate())
        self.time_class=QLineEdit()
        self.time_class.setFixedWidth(100)
        self.time_class.setPlaceholderText('填写时间段')
        self.student_class=QLineEdit()
        self.student_class.setPlaceholderText('请输入上课学生名，多个以英文逗号连接')
        self.push_class=QPushButton('添加课程')
        self.push_class.clicked.connect(self.add_classroom)
        create_class_layout.addWidget(self.date_class)
        create_class_layout.addWidget(self.time_class)
        create_class_layout.addWidget(self.student_class)
        create_class_layout.addWidget(self.push_class)
        create_class.setLayout(create_class_layout)
        from src.backend.datafactory import classroom
        self.df=classroom()
        self.calendar=NewCalendar(self.df,parent=self)
        # 连接点击事件

        self.calendar.clicked[QDate].connect(self.update_time_period)
        self.time_period_class = TimePeriod(1, 6,self)
        self.time_period_class.cellClicked.connect(self.on_time_clicked)

        self.layout = QVBoxLayout()
        self.layout.addWidget(create_class)
        self.layout.addWidget(self.calendar)
        self.layout.addWidget(self.time_period_class)
        self.setLayout(self.layout)

    def add_classroom(self):
        date=self.date_class.date()
        time=self.time_class.text()
        student=self.student_class.text()
        from src.backend.service.classroom import add_classroom
        add_classroom(ClassRoom(date,time,student))


    def update_time_period(self,date:QDate):
        time_period=self.df[self.df['date']==date.toString('yyyy-MM-dd')]['time_period'].values.tolist()
        self.time_period_class.update_item_color(time_period)


    def on_time_clicked(self,row,col):
        # 获取被点击的单元格
        item = self.time_period_class.item(row, col)
        if item.text() not in self.time_period_class.time_period:
            QMessageBox.warning(self,'警告','当前时间点没有课程')
            return
        date=self.calendar.selectedDate()
        if item:
            clicked_text = item.text()

        Classroomming(self).exec_()


class CustomTextEdit(QTextEdit):
    def __init__(self,dir, parent=None):
        super().__init__(parent)
        self.newPath=dir
        self.count=len(os.listdir(dir))

    def update_image_name(self,match):
        # 保存图片到新路径
        old_path = match.group(1)
        with open(old_path,'rb') as f2:
            code=f2.read()
        for path in os.listdir(self.newPath):
            with open(self.newPath+'\\'+path,'rb') as f1:
                if f1.read()==code:
                    return f'src="file:///{self.newPath}\\{path}"'
        name = str(self.count + 1) + '.' + old_path.split('.')[1]
        new_path = os.path.join(self.newPath, name)
        if not os.path.exists(new_path):
            self.count += 1
            # 从临时文件夹复制图片到新路径
            shutil.copy2(old_path, new_path)
        return f'src="file:///{new_path}"'

    def paste(self):
        clipboard= QApplication.clipboard()
        mimeData=clipboard.mimeData()
        if mimeData.hasHtml():
            html = mimeData.html()
            pattern = re.compile(r'src="file:///([^"]+)"')
            new_html = pattern.sub(lambda m: self.update_image_name(m), html)
            # if old_path:
            #     shutil.rmtree(os.path.dirname(old_path))
            self.setHtml(new_html)
            return new_html
        else:
            super().paste()  # 如果没有 HTML 内容，使用默认的粘贴行为

    def insertFromMimeData(self, source):
        if source.hasImage():
            # 处理直接粘贴的图像
            image = QImage(source.imageData())
            pixmap = QPixmap.fromImage(image)
            self.save_pixmap_and_insert(pixmap)
        elif source.hasHtml():
            self.paste()

        else:
            super().insertFromMimeData(source)
    #
    #

class Classroomming(QDialog):

    def __init__(self,parent=None):
        super(Classroomming, self).__init__(parent)
        self.setFixedSize(900, 600)
        self.paper_layout = QVBoxLayout()
        single = QWidget()
        single.setFixedHeight(200)
        single.setStyleSheet('border: 2px solid black;')
        single_layout = QHBoxLayout()
        self.textedit = CustomTextEdit(r'D:\ai\projects\python\homework\image')
        # self.textedit.setFixedHeight(150)
        self.textedit.setPlaceholderText('输入讲义信息')
        lineedit = QLineEdit('输入课程主题')
        single_layout.addWidget(self.textedit)
        single_layout.addWidget(lineedit)

        sub = QPushButton('切分')
        sub.clicked.connect(self.submit)
        sql_button = QPushButton('入库')
        sql_button.clicked.connect(self.insert_sqlite)
        com = QPushButton('生成报告')
        single_layout.addWidget(sub)
        single_layout.addWidget(sql_button)
        single_layout.addWidget(com)

        single.setLayout(single_layout)
        self.knowledge = Table_ABC()
        self.paper_layout.addWidget(single)
        self.paper_layout.addWidget(self.knowledge)
        self.setLayout(self.paper_layout)

    def insert_sqlite(self):
        data=self.knowledge.get_data()
        from src.backend.api.testpaper import correct_insert_sqlite
        correct_insert_sqlite(data)
        QMessageBox.information(self, "成功", "入库完成")

    def submit(self):
        html=self.textedit.toHtml()
        from src.backend.tools.file import parser_html
        questions=parser_html(html) #切题

        # 插入足够的行数
        self.knowledge.setRowCount(len(questions))
        self.knowledge.setColumnCount(3)
        self.knowledge.setHorizontalHeaderLabels(['题目','jj', 'uu'])
        self.knowledge.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        for row,p in enumerate(questions):
            for col in range(3):
                if col==0:
                    text = QTextEdit()
                    text.setHtml(str(p))
                    text.setReadOnly(True)
                # elif col==1:
                #     text=CustomQPushButton('删除',row,self.knowledge)
                else:
                    text=QLineEdit()
                self.knowledge.setCellWidget(row,col,text)

        # 手动设置所有行的高度
        for row in range(self.knowledge.rowCount()):
            self.knowledge.setRowHeight(row, 100)  # 设置每行高度为50像素
        # 自动调整所有列的宽度
        self.knowledge.resizeColumnsToContents()


class TimePeriod(QTableWidget):

    def __init__(self,row,col,parent=None):
        super().__init__()
        self.setColumnCount(col)
        self.setRowCount(row)
        self.setFixedHeight(80)
        self.setRowHeight(0, 80)
        # self.setFixedWidth(width)
        # 隐藏水平和垂直表头
        self.verticalHeader().setVisible(False)
        self.horizontalHeader().setVisible(False)
        # 设置表格的内容
        self.time_list = ['8-10', '10-12', '13-15', '15-17', '17-19', '19-21']
        for col in range(len(self.time_list)):
            item = QTableWidgetItem(self.time_list[col])
            # 设置文本居中对齐
            color=QBrush(QColor('red'))
            self.time_period=parent.df[parent.df['date'] == datetime.datetime.today().strftime('%Y-%m-%d')]['time_period'].values
            if self.time_list[col] in self.time_period:
                item.setBackground(color)
            item.setTextAlignment(Qt.AlignCenter)
            self.setItem(0, col, item)
            self.setColumnWidth(col, int(self.width() / 6))

    def update_item_color(self,time_period):
        self.time_period=time_period
        for t in self.time_list:
            item = QTableWidgetItem(t)
            color = QBrush(QColor('red')) if t in time_period else QBrush()
            item.setBackground(color)
            self.setItem(0, self.time_list.index(t), item)

class NewCalendar(QCalendarWidget):

    def __init__(self,df:DataFrame,parent=None):
        super(NewCalendar, self).__init__()
        self.setGridVisible(True)  # 显示网格
        self.setFixedHeight(350)
        self.df=df
        self.parent=parent
        self.highlighted_date=QDate.currentDate()
        self.selectionChanged.connect(self.update_color)
    def update_color(self):
        # 获取当前选中的日期
        selected_date = self.selectedDate()
        # 更新高亮日期
        self.highlighted_date = selected_date
        # 强制刷新日历显示
        self.updateCells()

    def paintCell(self, painter: QPainter, rect: QRect, date: QDate):
        if date == self.highlighted_date:  # 如果是高亮的日期
            # 设置背景色为红色
            painter.fillRect(rect, QColor(80, 0, 0))
            # 绘制日期数字，确保文本居中且颜色为白色
            painter.setPen(Qt.white)
            painter.drawText(rect, Qt.AlignCenter, str(date.day()))
            # 检查当前日期是否有自定义内容或颜色
        elif date.toString('yyyy-MM-dd') in self.df['date'].values:
            # 设置背景颜色
            painter.fillRect(rect, QBrush(QColor("#FF0000")))
            painter.save()  # 保存当前绘制状态
            painter.setPen(QPen(QColor("#000000"), 1))  # 设置文本颜色为黑色
            painter.setFont(QFont("Arial", 10))  # 设置字体和大小
            text = date.toString('d')  # 获取日期的文本表示
            painter.drawText(rect, Qt.AlignCenter,text)  # 手动计算文本位置并绘制
            painter.restore()  # 恢复绘制状态
        else:
            super().paintCell(painter, rect, date)

    def add_custom_content(self, date: QDate, content: str):
        self.custom_dates[date] = content
        self.updateCell(date)

    def clear_custom_content(self, date: QDate):
        if date in self.custom_dates:
            del self.custom_dates[date]
            self.updateCell(date)

